package com.jcodes.simple.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
public class LogHandlerInterceptor implements HandlerInterceptor {
    StopWatch stopWatch = new StopWatch();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        stopWatch.start(String.valueOf(handler));
        log.info("preHandle:\n{}\n{}\n{}", request, response, handler);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle:\n{}\n{}\n{}\n{}", request, response, handler, modelAndView);
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        stopWatch.stop();
        log.info("afterCompletion:\n{}\n{}\n{}\n{}\n{}", request, response, handler, ex,stopWatch.prettyPrint());
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
